-- MultiTouchDemo.lua
-- Author: Mikael Kindborg
-- Date: 2011-02-22
-- Description: Demo of multi-touch in Lua. There are
-- two rectangles that you can move using two fingers.

function DrawScreen()
  DrawBackground()
  DrawObjects()
  maUpdateScreen()
end

function DrawBackground()
  maSetColorRGB(0, 0, 255)
  maFillRect(0, 0, Screen.getWidth(), Screen.getHeight())
end

function DrawObjects()
  for i,object in ipairs(Objects) do 
    object.draw()
  end
end

function MoveObjects(x, y, touchId)
  if 0 == touchId then
    Objects[1].setPosition(x, y)
  elseif 1 == touchId then
    Objects[2].setPosition(x, y)
  end
end

function CreateObject(properties)
  local self = {}
  self.x = properties.x
  self.y = properties.y
  self.color = properties.color
  self.size = 100
  self.setPosition = function(x, y)
    self.x = x
    self.y = y
  end
  self.draw = function()
    maSetColorRGB(self.color[1], self.color[2], self.color[3])
    local halfSize = self.size / 2
    maFillRect(
      self.x - halfSize, 
      self.y - halfSize, 
      self.size, 
      self.size)
  end
  return self
end

-- Set touch functions.
System.onTouchDown(MoveObjects)
System.onTouchDrag(MoveObjects)

-- Create the objects you can move with the fingers.
Objects = 
{
  CreateObject { 
    x = 100, 
    y = 100,
    color = { 0, 255, 0 } },
  CreateObject { 
    x = 200, 
    y = 100,
    color = { 255, 255, 0 } }
}

-- Start timer that updates the screen.
-- This will start the screen updates.
Timer = System.startTimer(50, function() DrawScreen() end)

-- Stop timer interactively by evaluating this line.
-- System.stopTimer(Timer)
